package com.jnu.hc.jnuhcusercms.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.jnu.hc.jnuhcusercms.domain.Orders;
import com.jnu.hc.jnuhcusercms.domain.Setmeal;
import com.jnu.hc.jnuhcusercms.dto.ResponseObject;
import com.jnu.hc.jnuhcusercms.mapper.OrdersMapper;
import com.jnu.hc.jnuhcusercms.mapper.SetmealMapper;
import com.jnu.hc.jnuhcusercms.service.AlipayConfig;
import com.jnu.hc.jnuhcusercms.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class PayController {

    @RequestMapping("/pay/{orderId}/{cost}")
    public void pay(@PathVariable String orderId, @PathVariable String cost, HttpServletResponse response)  {
        try{AlipayClient alipayClient= AlipayConfig.getAlipayClient();
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setOutTradeNo(orderId);
        model.setTotalAmount(cost);
        model.setSubject("订单支付");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        alipayRequest.setBizModel(model);
        String url="http://localhost:8080/pay/success?orderId="+orderId+"";
        System.out.println(url);
        alipayRequest.setReturnUrl(url);
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(result);}
            catch(Exception e) {
                e.printStackTrace();
            }


    }
    @RequestMapping("/pay/success")
    public void success(@RequestParam("orderId") String orderId, HttpServletResponse response) throws IOException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String html = "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "   <script>" +
                "       setTimeout(() => {" +
                "           try {" +
                "               window.close();" +
                "           } catch (e) {" +
                "               document.body.innerHTML += '<p>请手动关闭窗口</p>';" +
                "           }" +
                "       }, 3000);" +
                "   </script>" +
                "</head>" +
                "<body>" +
                "   订单 " + orderId + " 支付成功！窗口3秒后自动关闭。" +
                "</body>" +
                "</html>";
        response.getWriter().println(html);
    }
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrdersService ordersService;
    @RequestMapping("/checkpayment")
    public ResponseObject checkpayment(@RequestBody Orders orders,@RequestParam Integer randomint){
        try {
            AlipayClient alipayClient= AlipayConfig.getAlipayClient();
            AlipayTradeQueryRequest request=new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model=new AlipayTradeQueryModel();
            String trno=orders.getUserId()+"A"+orders.getHpId()+"A"+orders.getSmId()+"A"+randomint;
            model.setOutTradeNo(trno);
            request.setBizModel(model);
            AlipayTradeQueryResponse response=alipayClient.execute(request);
            if(!response.isSuccess()){
                System.out.println("交易结果获取失败"+trno);
                return null;
            }
            if(response.getTradeStatus().equals("TRADE_SUCCESS")){
                System.out.println("交易成功"+trno);
                return ordersService.saveOrders(orders);
            }
        }catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Autowired
    SetmealMapper setmealMapper;

    @RequestMapping("/refund")
    public ResponseObject refund(@RequestBody Orders orders) throws AlipayApiException {
        Orders torder= ordersMapper.selectByPrimaryKey(orders.getOrderId());
        if(torder==null){
            return new ResponseObject(404,"该订单不存在");
        }
        System.out.println(torder.getTrno());
        System.out.println(torder.getOrderId());
        if(torder.getState()==2){
            return new ResponseObject(403,"该订单已完成，无法退款");
        }
        AlipayClient alipayClient= AlipayConfig.getAlipayClient();
        AlipayTradeRefundRequest request=new AlipayTradeRefundRequest();
        Setmeal setmeal=setmealMapper.selectByPrimaryKey(torder.getSmId());
        if(setmeal==null){
            return new ResponseObject(502,"查询订单时发生错误");
        }
        request.setBizContent("{\"out_trade_no\":\""+ torder.getTrno() +"\","
                        + "\"refund_amount\":\""+ setmeal.getPrice() +"\"}");
        AlipayTradeRefundResponse response =alipayClient.execute(request);
        if(response.getMsg().equals("Success")){
            ordersMapper.deleteByPrimaryKey(torder.getOrderId());
            return new ResponseObject(200,"退款请求返回成功",response.getMsg());
        }
        return new ResponseObject(501,"退款请求返回失败");

    }
}
